from datetime import datetime

from django.db.models import Q
from django.shortcuts import render, redirect

# Create your views here.
from room.models import rooms
from users.models import Users


def query(request):
    all_users = Users.objects.all()
    return render(request, 'users/userInfo2.html', {'user_list': all_users})


def delete(request, uid):
    user = Users.objects.get(id=uid)
    user.delete()
    return redirect('/udo/info/query')


def update(request, uid):
    if 'islogin' in request.session:
        user = Users.objects.get(id=uid)
        room_list = rooms.objects.filter(Q(status__exact=0) | Q(room_number__exact=user.room.room_number))
        return render(request, 'users/update.html', {'user': user, 'room_list': room_list})
    else:
        return render(request, '404.html')


def updatedo(request):
    new_id = request.POST.get('id')
    user = Users.objects.get(id=new_id)
    user.name = request.POST.get('name')
    new_room_number = request.POST.get('room_number')
    room = rooms.objects.get(room_number__exact=new_room_number)
    user.room = room
    user.phone_number = request.POST.get('phone_number')
    user.save()
    return redirect('/udo/info/query')


def roomsquery(request):
    room_list = Users.objects.all().order_by('address')
    return render(request, 'users/rooms.html', {'room_list': room_list})


def add(request):
    if 'islogin' in request.session:
        all_room = rooms.objects.filter(status__exact=0)
        return render(request, 'users/add.html', {'room_list': all_room})
    else:
        return render(request, '404.html')


def adddo(request):
    user = Users()
    user.name = request.POST.get('name')

    new_room_number = request.POST.get('room_number')
    print(new_room_number)
    room = rooms.objects.get(room_number__exact=new_room_number)
    # 默认员工输入的用户为已入住
    room.status = 1
    room.save()
    user.room = room
    gender = request.POST.get('gender')
    user.gender = gender
    user.phone_number = request.POST.get('phone_number')
    user.reg_date = datetime.now()
    user.status = 2
    user.save()
    return redirect('/udo/info/query')


def analysis_query(request):
    return render(request, 'users/useranalysis.html')
